package DBLayer;

import ModelLayer.Customer;
import Prototypes.CustomerResultSetModelBinder;
import Prototypes.DataLayer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBCustomerContainer extends DataLayer implements ICustomerContainer
{
    public DBCustomerContainer()
    {
        super();
    }

    public Customer getCustomer(int id)
    {
        try
        {
            String query = "SELECT * FROM WSCustomer WHERE CustomerID = " + id;
            Statement getStatement = dbConnection.createStatement();

            ResultSet results = getStatement.executeQuery(query);
            CustomerResultSetModelBinder binder = new CustomerResultSetModelBinder();
            
            return binder.BindModel(results);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(DBCustomerContainer.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }

    public ArrayList<Customer> getCustomers()
    {
        try
        {
            String query = "SELECT * FROM WSCustomer";
            Statement getStatement = dbConnection.createStatement();

            ResultSet results = getStatement.executeQuery(query);
            CustomerResultSetModelBinder binder = new CustomerResultSetModelBinder();

            return binder.BindModels(results);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(DBCustomerContainer.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    public boolean addCustomer(double totalSpent, int customerTypeID, int personID)
    {
        int noOfAffectedRows = -1;

        String query = "INSERT INTO WSCustomer(totalSpent, customerTypeID, personID) VALUES('"
                + totalSpent + "','"
                + customerTypeID + "','"
                + personID + "')";

        System.out.println(query);

        try
        {
            Statement stmt = dbConnection.createStatement();
            stmt.setQueryTimeout(5);
            noOfAffectedRows = stmt.executeUpdate(query);
            stmt.close();
        }
        catch (SQLException ex)
        {
            System.out.println("Insert exception in customer db; " + ex);
        }
        return noOfAffectedRows > 0;
    }
}
